
#include "IO.h"
#include "BSP_Delay.h"
#include "BSP_Config.h"

#include "usbd_std.h"
#include "custom_hid_core.h"

static const IO_T usbPullUp = {(void*)USB_PULLUP, USB_PULLUP_PIN};

/*!
    \brief      configure the different system clocks
    \param[in]  none
    \param[out] none
    \retval     none
*/
static void usb_rcu_config(void)
{
//	    /* enable USB pull-up pin clock */ 
//	    rcu_periph_clock_enable(RCC_AHBPeriph_GPIO_PULLUP);

    /* enable the power clock */
    rcu_periph_clock_enable(RCU_PMU);

    /* configure USB model clock from PLL clock */
    rcu_usb_clock_config(RCU_CKUSB_CKPLL_DIV1_5);

    /* enable USB APB1 clock */
    rcu_periph_clock_enable(RCU_USBD);
}


/*!
    \brief      configure the gpio peripheral
    \param[in]  none
    \param[out] none
    \retval     none
*/
static void usb_gpio_config(void)
{
    /* configure usb pull-up pin */
	IO_Init(&usbPullUp, IO_Mode_OUT);
	IO_Set(&usbPullUp, !USB_PULLUP_ENABLE);
}

/*!
    \brief      configure interrupt priority
    \param[in]  none
    \param[out] none
    \retval     none
*/
static void usb_nvic_config(void)
{
    /* 1 bit for pre-emption priority, 3 bits for subpriority */
//	    nvic_priority_group_set(NVIC_PRIGROUP_PRE1_SUB3);

    /* enable the USB low priority interrupt */
    nvic_irq_enable(USBD_LP_CAN0_RX0_IRQn, 2, 0);
}

/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/
void BSP_USB_Init(void)
{
    /* system clocks configuration */
    usb_rcu_config();

    /* GPIO configuration */
    usb_gpio_config();

//	    /* USB device configuration */
//	    usbd_core_init(&usb_device_dev);

}

void BSP_USB_Deinit(void){
	nvic_irq_disable(USBD_LP_CAN0_RX0_IRQn);
}


void BSP_USB_Connect(uint8_t state){
	/* NVIC configuration */
	usb_nvic_config();
    /* enabled USB pull-up */
//	    gpio_bit_set(USB_PULLUP, USB_PULLUP_PIN);
	if(state){
		IO_Set(&usbPullUp, USB_PULLUP_ENABLE);
	}
	else{
		IO_Set(&usbPullUp, !USB_PULLUP_ENABLE);
	}
}


